package com.ip.user.api;

import com.ip.user.config.JwtTokenUtil;
import com.ip.user.models.bo.UserBO;
import com.ip.user.models.dto.UserLoginDTO;
import com.ip.user.models.dto.UserRegisterDTO;
import com.ip.user.models.service.SysUserService;
import com.ip.user.models.vo.UserVO;
import com.ip.user.util.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录注册控制器
 * author 刘丰源
 */
@RestController
@RequestMapping("/api/auth")
@CrossOrigin
public class LoginController {
    
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    
    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private TokenUtil tokenUtil;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        try {
            UserVO sysUser = sysUserService.registerUser(userRegisterDTO);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "注册成功");
            response.put("data", sysUser);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody UserLoginDTO userLoginDTO) {
        try {
            String userName = userLoginDTO.getUserName();
            logger.info("User login attempt: {}", userName);
            
            // 用户登录验证
            if (userName == null || userName.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户名不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            UserVO sysUser = sysUserService.login(userLoginDTO);
            
            // 生成JWT token
            UserDetails userDetails = new User(sysUser.getUserName(), "", new ArrayList<>());
            String token = jwtTokenUtil.generateToken(userDetails);
                        
            logger.info("Generated token for user: {}", sysUser.getUserName());
            
            // 实现单设备登录
            tokenUtil.saveUserToken(userName, token);
                        
            logger.info("Saved token for user: {}", userName);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("data", sysUser);
            response.put("token", token);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            if (token != null) {
                // 处理可能带有Bearer前缀的token
                if (token.startsWith("Bearer ")) {
                    token = token.substring(7);
                }
                String userName = jwtTokenUtil.getUsernameFromToken(token);
                tokenUtil.removeUserToken(userName);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "登出成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public ResponseEntity<?> getCurrentUser(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            if (token != null) {
                // 处理可能带有Bearer前缀的token
                if (token.startsWith("Bearer ")) {
                    token = token.substring(7);
                }
                
                String userName = jwtTokenUtil.getUsernameFromToken(token);
                
                // 验证token有效性（单设备登录）
                if (!tokenUtil.validateUserToken(userName, token)) {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", "登录已失效，请重新登录");
                    // 返回401未授权状态码而不是400错误请求状态码
                    return ResponseEntity.status(401).body(response);
                }
                
                UserVO sysUser = sysUserService.getUserByUserName(userName);
                
                if (sysUser != null) {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("data", sysUser);
                    return ResponseEntity.ok(response);
                }
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户未登录");
            // 返回401未授权状态码而不是400错误请求状态码
            return ResponseEntity.status(401).body(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}